import router from "@/router"
import { defineStore } from "pinia"
import { getShowMenuList, getFlatMenuList, getAllBreadcrumbList } from "@/utils/index"
import { TabsState, TabsMenuProps } from "@/store/interface"

export const useRouterStore = defineStore({
  id: "router-control",
  state: (): TabsState => {
    return {
      initMenu: [],
      tabsMenuList: [],
      currentPath: "",
      isCollapse: false
    }
  },
  getters: {
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    initMenuList: (state) => state.initMenu,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuList: (state) => getShowMenuList(state.initMenu),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuList: (state) => getFlatMenuList(state.initMenu),
    // 递归处理后的所有面包屑导航列表
    breadcrumbList: (state) => getAllBreadcrumbList(state.initMenu)
  },
  actions: {
    async setInitMenu(val: Menu.MenuOptions[]) {
      ;(this.initMenu as Menu.MenuOptions[]) = val
    },
    async setPath(val: string) {
      this.currentPath = val
    },
    // Add Tabs
    async addTabs(tabItem: TabsMenuProps) {
      if (this.tabsMenuList.every((item) => item.path !== tabItem.path)) {
        this.tabsMenuList.push(tabItem)
      }
    },
    // Remove Tabs
    async removeTabs(tabPath: string, isCurrent: boolean = true) {
      const tabsMenuList = this.tabsMenuList
      if (isCurrent) {
        tabsMenuList.forEach((item, index) => {
          if (item.path !== tabPath) return
          const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1]
          if (!nextTab) return
          router.push(nextTab.path)
        })
      }
      this.tabsMenuList = tabsMenuList.filter((item) => item.path !== tabPath)
    },
    async setCollapse() {
      this.isCollapse = !this.isCollapse
    }
  },
  persist: true
})
